<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Wxlitestoregoods;
use app\admin\model\litestore\Litestorecategory;
use app\admin\model\litestore\Litestorefreightrule;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestorenews;
use app\admin\model\litestore\Litestoreorder;
use app\admin\model\litestore\Litestoreorderaddress;
use app\admin\model\litestore\Litestoreordergoods;
use app\admin\model\Litestoreactive;
use app\admin\model\Shop;
use app\admin\model\Useraddress;
use app\admin\model\Usercard;
use app\admin\model\Userotherprofit;
use app\admin\model\Userscore;
use app\admin\model\Userverify;
use app\admin\model\Userweixin;
use app\admin\model\Userwx;
use app\api\service\BankService;
use app\api\service\CardService;
use app\api\service\MallService;
use app\api\service\MessageService;
use app\api\service\ProfitService;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\model\Area;
use EasyWeChat\Factory;
use fast\Http;
use OSS\OssClient;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;


class Mall extends Api
{
    protected $noNeedLogin = ['cate','cateList', 'index','index2', 'category_list', 'detail', 'sxfOrderCallback','alipayNotify','randomProduct','subCate','cateList2','wechatNotify','cateList3'];
    protected $noNeedRight = '*';


    protected $app;
    public function _initialize()
    {
        parent::_initialize();

        $config = [
            'app_id' => 'wxa450f239e42c26fe',
            'secret' => 'f23092b77af8aa3c242b49a96689c27f',
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
            ],
        ];
        $this->app = Factory::miniProgram($config);

    }

    public function index()
    {

        $listoreGoodNewsModel = new Litestorenews();
        $page = $this->request->param('page');
        $banner = $listoreGoodNewsModel->select();
        foreach ($banner as $key => $val) {
            $banner[$key]['image'] = cdnurl($val['image'], true);
        }
        // 筛选条件
        $filter = [];
        $filter['is_recommend'] = 1;

        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';

        $sort = ['goods_sort' => 'desc', 'goods_id' => 'desc'];

        // 商品表名称
        $model_temp = new Wxlitestoregoods();
        $tableName = $model_temp->getTable();
        // 多规格商品 最高价与最低价
        $GoodsSpec = new Litestoregoodsspec();
        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',
            "$minPriceSql AS goods_min_price",
            "$maxPriceSql AS goods_max_price"
        ])->with(['spec'])->where($filter)->order($sort)
            ->paginate(10, false, [ 'page' => $page ]);

        $blistdatarList = [];
        foreach ($listdata as $index => $item) {
            $blistdatarList[] = ['image' => cdnurl(explode(",",$item['images'])[0], true), 'goods_name' => $item['goods_name'],
                'id'=> $item['goods_id'],'goods_min_price'=>$item['goods_min_price'],'goods_max_price'=>$item['goods_max_price'],'goods_sales'=>$item['goods_sales'],'num'=>1,'count'=>'0'];
        }

        $ret = array();
        $ret['banner'] = $banner;
        $ret['recommend'] = $blistdatarList;

        $this->success('', $ret);


    }


    public function index2()
    {

        $listoreGoodNewsModel = new Litestorenews();
        $banner = $listoreGoodNewsModel->select();
        foreach ($banner as $key => $val) {
            $banner[$key]['image'] = cdnurl($val['image'], true);
        }
        $litestoreActiveModel = new Litestoreactive();
        $list = $litestoreActiveModel->where('is_data',1)->order('is_max','desc')->select();
        foreach ($list as $key => $val) {
            $list[$key]['image'] = cdnurl($val['image'], true);
        }

        // 筛选条件
        $filter = [];
        $filter['is_recommend'] = 1;

        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';

        // 排序规则
        $sort = [];
        $sort = ['goods_sort' => 'desc', 'goods_id' => 'desc'];


        $litestoreGoodModel = new Litestoregoods();
        $list  = $litestoreGoodModel->where($filter)->order($sort)
            ->paginate(3, false, ['page' => 1]);

        $blistdatarList = [];
        foreach ($list as $index => $item) {
            $blistdatarList[] = ['line_price'=>$item['market_price'],'image' => cdnurl(explode(",", $item['images'])[0], true), 'goods_name' => $item['goods_name'],
                'id' => $item['goods_id'], 'goods_min_price' => $item['sale_price'], 'goods_max_price' => $item['sale_price'], 'goods_sales' => $item['goods_sales']];
        }



        $ret = array();
        $ret['banner'] = $banner;
        $ret['active'] = $list;
        $ret['recommend'] = $blistdatarList;


        $this->success('', $ret);


    }

    /**
     * 分类
     */
    public function cate()
    {

        $listoreCateModel = new Litestorecategory();
        $list = $listoreCateModel->where('pid','<>',0)->order('weigh', 'desc')->select();
        $this->success('', $list);
    }

    public function subCate()
    {

        $id = $this->request->param('id');
        $listoreCateModel = new Litestorecategory();
        $list = $listoreCateModel->where('pid',$id)->order('weigh', 'desc')->select();
        $this->success('', $list);
    }



    /**
     * 一级分类
     */
    public function cateList(){
        $listoreCateModel = new Litestorecategory();
        $list = $listoreCateModel->where('pid',0)->order('weigh', 'asc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }
        $this->success('', $list);


    }
    public function cateList2(){
        $listoreCateModel = new Litestorecategory();
        $list = $listoreCateModel->where('name',"<>",'金融服务')->where('pid',0)->order('weigh', 'asc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }
        $this->success('', $list);


    }
    public function cateList3(){
        $listoreCateModel = new Litestorecategory();

        $list = $listoreCateModel->where('pid',0)->order('weigh', 'asc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }
        $this->success('', $list);


    }

    public function wxCateList(){
        $listoreCateModel = new Litestorecategory();

        $list = $listoreCateModel->where('name',"<>",'金融服务')->where('pid',0)->order('weigh', 'asc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }
        $this->success('', $list);


    }

    public function cateList4(){
        $listoreCateModel = new Litestorecategory();

        $list = $listoreCateModel->where('pid',0)->order('weigh', 'asc')->select();
        foreach ($list as $key=>$val){
            $list[$key]['image'] = cdnurl($val['image'],true);
        }
        $this->success('', $list);


    }


    public function category_list()
    {
        $categoryid = $this->request->param('id');
        $page = $this->request->param('page');
        $sortType = $this->request->param('types');
        $rename = $this->request->param('name');
        $is_recommend = $this->request->param('is_recommend');

        // 筛选条件
        $filter = [];

        if ($categoryid != "") {
            $filter['category_id'] = $categoryid;
        }

        if($is_recommend != ""){
            $filter['is_recommend'] = $is_recommend;

        }

        if($rename != ''){
            $filter['goods_name'] = ['like', '%' . trim($rename) . '%'];
        }



        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';

        // 排序规则
        $sort = [];
        if ($sortType === 'normal') {
            $sort = ['goods_sort' => 'desc', 'goods_id' => 'desc'];
        } elseif ($sortType === 'sales') {
            $sort = ['goods_sales' => 'desc'];
        } elseif ($sortType === 'price') {
            $sort = ['goods_min_price' => 'asc'];
        }

        error_log("==filter===".json_encode($filter));
        $model_temp = new Wxlitestoregoods();
        $tableName = $model_temp->getTable();
        // 多规格商品 最高价与最低价
        $GoodsSpec = new Litestoregoodsspec();
        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',
            "$minPriceSql AS goods_min_price",
            "$maxPriceSql AS goods_max_price"
        ])->with(['spec'])->where($filter)->order($sort)
            ->paginate(10, false, [ 'page' => $page ]);

        $blistdatarList = [];
        foreach ($listdata as $index => $item) {
            $blistdatarList[] = ['image' => cdnurl(explode(",",$item['images'])[0], true), 'goods_name' => $item['goods_name'],
                'id'=> $item['goods_id'],'goods_min_price'=>$item['goods_min_price'],'goods_max_price'=>$item['goods_max_price'],'goods_sales'=>$item['goods_sales'],'num'=>1,'count'=>'0'];
        }


        $this->success('成功', $blistdatarList);


    }


    public function active_list()
    {
        $categoryid = $this->request->param('id');
        $page = $this->request->param('page');
        $sortType = $this->request->param('types');
        $rename = $this->request->param('name');
        $active = $this->request->param('active_id');
        $is_index = $this->request->param('is_index');

        // 筛选条件
        $filter = [];

        if ($categoryid != "") {
            $filter['category_id'] = $categoryid;
        }
        if($is_index != ''){
            $filter['is_index'] = $is_index;

        }

        if($rename != ''){
            $filter['goods_name'] = ['like', '%' . trim($rename) . '%'];
        }

        if($active != ''){
            $filter['active_id'] = $active;
        }

        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';

        // 排序规则
        $sort = [];
        if ($sortType === 'normal') {
            $sort = ['goods_sort' => 'desc', 'goods_id' => 'desc'];
        } elseif ($sortType === 'sales') {
            $sort = ['goods_sales' => 'desc'];
        } elseif ($sortType === 'price') {
            $sort = ['goods_min_price' => 'asc'];
        }

        error_log("==filter===".json_encode($filter));

        $litestoreGoodModel = new Litestoregoods();
        $list  = $litestoreGoodModel->where($filter)->order($sort)
            ->paginate(20, false, ['page' => $page]);

        $blistdatarList = [];
        foreach ($list as $index => $item) {
            $blistdatarList[] = ['category_id'=>$item['category_id'],'line_price'=>$item['market_price'],'image' => cdnurl(explode(",", $item['images'])[0], true), 'goods_name' => $item['goods_name'],
                'id' => $item['goods_id'], 'goods_min_price' => $item['sale_price'], 'goods_max_price' => $item['sale_price'], 'goods_sales' => $item['goods_sales']];
        }

        $this->success('成功', $blistdatarList);


    }


    public function detail()
    {
        $goods_id = $this->request->param('goods_id');
        // 商品详情
        $detail = Wxlitestoregoods::detail($goods_id);
        $imgs = [];
        foreach (explode(",", $detail['images']) as $index => $item) {
            $imgs[] = cdnurl($item, true);
        }
        $detail['imgs_url'] = $imgs;

        if (preg_match('/(http:\/\/)|(https:\/\/)/i',  $detail['content'])) {
            $url = "";
        } else {
            $url = "https:";
        }
        $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
        $detail['content'] = preg_replace($pregRule, '<img src="' . $url . '${1}" style="max-width:100%">', $detail['content']);

        $userProfit = 0;
        if (!$detail || $detail['goods_status'] !== '10') {
            $this->error('很抱歉，商品信息不存在或已下架');
        }

        $user = $this->auth->getUser();
        $litestoreGoodSpecModel = new \app\admin\model\litestore\Litestoregoodsspec();
        $spec = $litestoreGoodSpecModel->where('goods_id',$goods_id)->find();


        // 规格信息
        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;

        // 这里对规格的img格式化
        if ($specData != null) {
            foreach ($specData['spec_list'] as $index => $item) {
                $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image'] === '' ? null : cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);
            }
        }




        $this->success('', [
            'detail' => $detail,
            'specData' => $specData,
            'profit' =>round($userProfit,2)
        ]);
    }


    /**
     * 添加地址
     */


    public function addAddress()
    {

        $user = $this->auth->getUser();
        $username = $this->request->param('username');
        $mobile = $this->request->param('mobile');
        $address = $this->request->param('detail');
        $provinceName = $this->request->param('province');
        $areaName = $this->request->param('area');
        $cityName = $this->request->param('city');

        $areaModel = new \app\admin\model\Area();
        $province = $areaModel->where('name', $provinceName)->find();
        if ($province == null) {
            $this->error('城市数据不对，请联系客服');
            error_log("========城市数据不对，请联系客服====pid========" . json_encode($provinceName));
        }
        $city = $areaModel->where('name', $cityName)->find();


        if ($city == null) {
            $this->error('城市数据不对，请联系客服');
            error_log("========城市数据不对，请联系客服====cid========" . json_encode($cityName));

        }
        $area = $areaModel->where('name', $areaName)->find();

        if ($area == null) {
            $this->error('城市数据不对，请联系客服');
            error_log("========城市数据不对，请联系客服====cid========" . json_encode($areaName));

        }


        $userAddressModel = new Useraddress();
        $userAddressModel->insert(['name' => $username, 'phone' => $mobile, 'detail' => $address,
            'user_id' => $user['id'], 'createtime' => time(),
            'province_id' => $province['id'], 'city_id' => $city['id'], 'region_id' => $area['id'], 'province' => $province['name'],
            'city' => $city['name'], 'area' => $area['name']]);
        $this->success('');

    }

    public function addressList()
    {

        $user = $this->auth->getUser();

        $where = array();
        $keyword = $this->request->param('keyword');
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['phone'] = array('like', '%' . $keyword . '%');
            } else {
                $where['name'] = array('like', '%' . $keyword . '%');
            }
        }
        $where['user_id'] = $user["id"];
        $userAddressModel = new \app\admin\model\Useraddress();
        $list = $userAddressModel->where($where)->select();
        $this->success('', $list);
    }


    public function editAddress()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $username = $this->request->param('username');
        $mobile = $this->request->param('mobile');
        $address = $this->request->param('detail');
        $provinceName = $this->request->param('province');
        $areaName = $this->request->param('area');
        $cityName = $this->request->param('city');


        $areaModel = new Area();
        $province = $areaModel->where('name', $provinceName)->find();
        if ($province == null) {
            $this->error('城市数据不对，请联系客服');
            error_log("========城市数据不对，请联系客服====pid========" . json_encode($provinceName));
        }
        $city = $areaModel->where('name', $cityName)->find();


        if ($city == null) {
            $this->error('城市数据不对，请联系客服');
            error_log("========城市数据不对，请联系客服====cid========" . json_encode($cityName));

        }
        $area = $areaModel->where('name', $areaName)->find();

        if ($area == null) {
            $this->error('城市数据不对，请联系客服');
            error_log("========城市数据不对，请联系客服====cid========" . json_encode($areaName));

        }

        $userAddressModel = new \app\admin\model\Useraddress();
        $userAddressModel->where('id', $id)->update(['name' => $username, 'phone' => $mobile, 'detail' => $address,
            'user_id' => $user['id'], 'createtime' => time(),
            'province_id' => $province['id'], 'city_id' => $city['id'], 'region_id' => $area['id'], 'province' => $province['name'],
            'city' => $city['name'], 'area' => $area['name']]);
        $this->success('');

    }

    public function deleteAddress()
    {
        $id = $this->request->param('id');
        $user = $this->auth->getUser();
        $userAddressModel = new \app\admin\model\Useraddress();
        $userAddressModel->where(['user_id' => $user['id'], 'id' => $id])->delete();
        $this->success('');
    }

    public function cacFee(){
        $addressId = $this->request->param('addressId');
        $goods = $this->request->param('goods');
        $items = json_decode(htmlspecialchars_decode($goods), true);
        $litestoregoodsspec = new Litestoregoodsspec();
        $userAddressModel = new Useraddress();
        $mallService = new MallService();
        $userAddressModel = new Useraddress();
        $address = $userAddressModel->where('id', $addressId)->find();
        if (!$address) {
            $this->error('请添加收货地址');
        }
        $listoreGoodModel = new Litestoregoods();

        $expressAmount =0;
        foreach ($items as $key => $val) {
            $good = $litestoregoodsspec->where('goods_id', $val['goods_id'])->where('spec_sku_id', $val['skuId'])->find();
            $goods = $listoreGoodModel->where('goods_id',$val['goods_id'])->find();

            $feeParam = array();
            $feeParam['address'] = $address;
            $feeParam['sku_id'] = $good['option_id'];
            $feeParam['num'] = $val['count'];

            if($goods['data_id'] != '' && $goods['category_id'] != 136){
                $expressAmount +=  $mallService->getFee($feeParam);
            }
        }
        $this->success('',$expressAmount);

    }



    public function addOrder()
    {


        $goods = $this->request->param('goods');
        $pay_type = $this->request->param('pay_type');
        $addressId = $this->request->param('addressId');
        $shopId = $this->request->param('shopId');

        $items = json_decode(htmlspecialchars_decode($goods), true);

        $user = $this->auth->getUser();
        $litestoregoodsspec = new Litestoregoodsspec();
        $userAddressModel = new Useraddress();
        $address = $userAddressModel->where('id', $addressId)->find();
        if (!$address) {
            $this->error('请添加收货地址');
        }
        $totalAmount = 0;
        $totalCount = 0;
        $str = "";
        $profit = 0;

        $expressAmount = 0;
        $payAmount = 0;
        $is_vip = -1;
        $listoreGoodModel = new Litestoregoods();

        $custPrice = 0;
        foreach ($items as $key => $val) {
            $good = $litestoregoodsspec->where('goods_id', $val['goods_id'])->where('spec_sku_id', $val['skuId'])->find();
            if ($key <= 2) {
                $str .= $val['goods_name'] . ",";
            }

            $goods = $listoreGoodModel->where('goods_id', $val['goods_id'])->find();
            if ($goods['category_id'] == 43) {
                $is_vip = 1;
            }


            error_log("===good===" . json_encode($good));
            $totalPrice = bcmul($good['goods_price'], $val['count'], 2);
            $items[$key]['totalPrice'] = $totalPrice;
            $items[$key]['price'] = $good['goods_price'];
            $totalCount += $val['count'];
            $totalAmount = $totalAmount + $totalPrice;
            $profit += ($totalPrice - $custPrice);
        }
        $data = array();


        $orderNo = getOrderSn();

        $totalAmount = round($totalAmount + $expressAmount, 2);

        $data['orderNo'] = $orderNo;
        $data['amount'] = $totalAmount;
        $data['address'] = $address;
        $data['goods'] = $items;
        $data['count'] = $totalCount;
        $data['express_amount'] = $expressAmount;
        $data['pay_type'] = $pay_type;
        $data['shopId'] = $shopId;


        $pay = round($data['amount'], 2);
        $data['pay_amount'] = $pay;
        $liteorder = new Litestoreorder();
        $orderId = $liteorder->addOrder($user['id'], $data);

        if ($orderId) {
            $info = array();
            $info['orderNo'] = $orderNo;

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mall/sxfOrderCallback";


            $req['mno'] = "399240109959044";
            $req['ordNo'] = $orderNo;
            $req['amt'] = $pay;


            $req['subject'] = "采购购买";
            $req['appletSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            $vbillService = new VbillService();
            $res = $vbillService->pay($req);

            error_log("--=====pay===".json_encode($res));
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $orderNo;
                $info['appId'] = $result['respData']['appId'];
                $info['path'] = $result['respData']['path'];

                $this->success('', $info);
            } else {
                $this->error($bizMsg);
            }

            $this->success('下单成功', $info);
        } else {
            $this->error("下单失败，请联系客服");
        }

    }


    public function sxfOrderCallback()
    {

        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);
            $listoreModel = new Litestoreorder();
            $order = $listoreModel->where('order_no', $out_trade_no)->find();
            $listoreModel->where('order_no', $out_trade_no)->update(['pay_status' => '20', 'pay_time' => time()]);


        }

    }





    public function wxAddOrder()
    {


        $goods = $this->request->param('goods');
        $pay_type = $this->request->param('pay_type');
        $addressId = $this->request->param('addressId');
        $code = $this->request->param('code');

        $items = json_decode(htmlspecialchars_decode($goods), true);

        $user = $this->auth->getUser();
        $litestoregoodsspec = new Litestoregoodsspec();
        $userAddressModel = new Useraddress();
        $address = $userAddressModel->where('id', $addressId)->find();
        if (!$address) {
            $this->error('请添加收货地址');
        }
        $totalAmount = 0;
        $totalCount = 0;
        $str = "";
        $profit = 0;

        $expressAmount = 0;
        $payAmount = 0;

        $listoreGoodModel = new Litestoregoods();
        error_log("==item==".json_encode($items));
        $litestoreCategoryModel = new Litestorecategory();
        $is_vip = -1;
        $is_self = -1;
        $mallService = new MallService();
        $custPrice = 0;
        foreach ($items as $key => $val) {
            $good = $litestoregoodsspec->where('goods_id', $val['goods_id'])->where('spec_sku_id', $val['skuId'])->find();
            if ($key <= 2) {
                $str .= $val['goods_name'] . ",";
            }
            $cate = $litestoreCategoryModel->where('name','会员升级')->find();
            $goods = $listoreGoodModel->where('goods_id',$val['goods_id'])->find();
            if($cate){
                if($goods['category_id'] == $cate['id']){
                    $is_vip = 1;
                }
            }
            $feeParam = array();
            $feeParam['address'] = $address;
            $feeParam['sku_id'] = $good['option_id'];
            $feeParam['num'] = $val['count'];

            if($goods['data_id'] != ''){
                $expressAmount +=  $mallService->getFee($feeParam);
            }

            if($goods['is_self'] == 1){
                $is_self = 1;
            }



            error_log("===good===".json_encode($good));
            $totalPrice = bcmul($good['goods_price'], $val['count'], 2);
            $custPrice = bcmul($good['cost_price'], $val['count'], 2);
            $items[$key]['totalPrice'] = $totalPrice;
            $items[$key]['price'] = $good['goods_price'];
            $totalCount += $val['count'];
            $totalAmount = $totalAmount + $totalPrice;
            $profit += ($totalPrice - $custPrice);
        }
        $data = array();


        $orderNo = "F".getOrderSn();

        $totalAmount = round($totalAmount+ $expressAmount, 2);

        $data['orderNo'] =$orderNo;
        $data['amount'] = $totalAmount;
        $data['address'] = $address;
        $data['goods'] = $items;
        $data['count'] = $totalCount;
        $data['express_amount'] = $expressAmount;
        $data['pay_type'] = $pay_type;
        $data['is_vip'] = $is_vip;
        $data['cost_price'] = $custPrice;
        $data['is_self'] = $is_self;




        $userWxModel = new Userwx();
        $wx = $userWxModel->where('user_id', $user['id'])->find();
        $openid = "";
        if(!$wx){
            $ret = $this->app->auth->session($code);
            error_log("====ret====".json_encode($ret));
            if (isset($ret["errcode"]) && $ret['errcode'] == '40163') {
                $this->error('请重新获取code');
            } else {
                $openid = $ret['openid'];
                $userWxModel->insert(['openid' => $openid, 'user_id' => $user['id']]);
            }
        }else{
            $openid = $wx['openid'];
        }



        $pay = round($data['amount'], 2);
        $data['pay_amount'] = $pay ;
        $liteorder = new Litestoreorder();
        $orderId = $liteorder->addOrder($user['id'],$data);
        $params = [
            'out_trade_no' => $orderNo,//你的订单号
            'total_amount' => $totalAmount,//单位元
            'subject'      => $str,
        ];
        if ($orderId) {
            $info = array();
            $info['orderNo'] = $orderNo;

            if($pay_type == 'wechat'){

                $params = [
                    'out_trade_no' => $orderNo,//你的订单号
                    'total_fee' => $totalAmount * 100,//单位元
                    'body' => $str,
                    'openid' => $openid,
                ];
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mall/wechatNotify";
                $config = Service::getConfig($pay_type);
                $config['notify_url'] = $url;
                $pay = Pay::wechat($config);
                $result = $pay->miniapp($params);
                $info['payInfo'] = json_decode($result,true);
                $this->success('下单成功', $info);
            }else{

                $config = Service::getConfig($pay_type);
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mall/alipayNotify";

                $config['notify_url'] = $url;
                $pay = Pay::alipay($config);
                $result = $pay->app($params)->getContent();
                $info['payInfo'] = $result;

            }
            $this->success('下单成功', $info);
        } else {
            $this->error("下单失败，请联系客服");
        }

    }


    public function orderList()
    {

        $user = $this->auth->getUser();

        $page = $this->request->param('page');
        $status = $this->request->param('status');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        error_log("==user===" . json_encode($user));
        $where = [];
        $where['user_id'] = $user['id'];
        if($status != ""){
            if ($status == 'payed') {
                $where['pay_status'] = '20';
                $where['freight_status'] = '10';
                $where['order_status'] = '10';

            } else if ($status == 'transit') {
                $where['pay_status'] = '20';
                $where['freight_status'] = '20';
                $where['order_status'] = '10';
            } else if ($status == 'done') {
                $where['order_status'] = '30';
            } else if($status == 'paying'){
                $where['pay_status'] = '10';
                $where['order_status'] = '10';
            }
        }


        error_log("===where==".json_encode($where));
        $litestoreorder = new Litestoreorder();
        $list = $litestoreorder->with(['goods'])
            ->where($where)
            ->order(['createtime' => 'desc'])->limit($offset, $limit)
            ->select();

        $newList = [];
        foreach ($list as $key => $val) {

            if ($val['pay_status'] == '10' && $val['order_status'] == '10') {
                $list[$key]['status'] = '待支付';
            } else if ($val['pay_status'] == '20' && $val['freight_status'] == '10') {
                $list[$key]['status'] = '待发货';
            } else if ($val['pay_status'] == '20' && $val['receipt_status'] == '10') {
                $list[$key]['status'] = '待收货';
            } else if ($val['order_status'] == '30') {
                $list[$key]['status'] = '已完成';
            }else{
                $list[$key]['status'] = '已取消';

            }
            $obj = [];
            $obj['status'] = $val['status'];
            $obj['orderNo'] = $val['order_no'];
            $obj['total_price'] = $val['total_price'];
            $obj['total_price'] = $val['total_price'];

            $obj['createtime'] = date("Y-m-d H:i:s", $val['createtime']);
            $goods = $val['goods'];
            $good = array();
            $totalCount = 0;
            foreach ($goods as $k => $v) {
                $goodObj = array();
                $goodObj['good_name'] = $v['goods_name'];
                $goodObj['num'] = $v['total_num'];
                $goodObj['price'] = $v['goods_price'];

                $goodObj['image'] = cdnurl(explode(",", $v['images'])[0], true);
                $good[] = $goodObj;
                $totalCount += $v['total_num'];
            }
            $obj['totalCount'] = $totalCount;
            $obj['goods'] = $good;
            $newList[] = $obj;

        }

        $this->success('', $newList);


    }


    public function orderDetail()
    {

        $orderNo = $this->request->param('orderNo');
        $liteOrderModel = new Litestoreorder();
        $order = $liteOrderModel->where('order_no', $orderNo)->find();
        $liteorderGoods = new Litestoreordergoods();
        $orderGood = $liteorderGoods->where('order_id', $order['id'])->select();
        foreach ($orderGood as $key => $val) {

            $orderGood[$key]['image'] = cdnurl(explode(",", $val['images'])[0], true);
        }

        $orderAddressModel = new Litestoreorderaddress();
        $address = $orderAddressModel->where('order_id', $order['id'])->find();


        $areaModel = new \app\admin\model\Area();
        $provice = $areaModel->where('id',$address['province_id'])->find();
        $city = $areaModel->where('id',$address['city_id'])->find();
        $area = $areaModel->where('id',$address['region_id'])->find();

        $address['province'] = $provice;
        $address['city'] = $city;
        $address['area'] = $area;

        $data = array();
        $data['goods'] = $orderGood;
        $data['address'] = $address;


        if ($order['pay_status'] == '10' && $order['order_status'] == '10') {
            $order['status'] = '待支付';
        } else if ($order['pay_status'] == '20' && $order['freight_status'] == '10') {
            $order['status'] = '待发货';
        } else if ($order['pay_status'] == '20' && $order['receipt_status'] == '10') {
            $order['status'] = '待收货';
        } else if ($order['order_status'] == '30') {
            $order['status'] = '已完成';
        }else if($order['order_status'] == '20'){
            $order['status'] = '已取消';
        }
        $order['createtime']= date("Y-m-d H:i:s",$order['createtime']);
        $data['order'] = $order;

        $this->success('', $data);
    }

    public function wechatNotify(){


        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee']/100;
        error_log("==wechat===result====".json_encode($result));
        $listoreModel =new Litestoreorder();
        if (in_array($result['return_code'], ['SUCCESS'])) {
            $order = $listoreModel->where('order_no',$out_trade_no)->find();
            $listoreModel->where('order_no',$out_trade_no)->update(['pay_status'=>'20','pay_time'=>time()]);
            $profitService = new ProfitService();
            if($order['is_vip'] == 1){
                $profitService->doUserVipProfit($order,$this->countRedis);

                if($order['is_do'] == 1) return;

                $messageService = new MessageService();
                $userProfitModel = new Userotherprofit();
                $userWxModel= new Userweixin();
                $profitList = $userProfitModel->where('type','会员升级')->where('order_id',$order['id'])->select();
                foreach ($profitList as $key=>$val){
                    $wx = $userWxModel->where('user_id',$val['user_id'])->find();
                    if($wx){
                        $param = array();
                        $param['openid'] = $wx['openid'];
                        $param['amount'] = $val['amount'];
                        $messageService->userProfitMessage($this->wxApp,$param);
                    }
                }
            }else{

                $mallService = new MallService();
                $req = array();
                $req['order_no'] = $out_trade_no;
                $mallService->addOrder($req);
            }
        }
        return $pay->success();

    }


    public function alipayNotify(){


        error_log("======alipayNotify=======");
        $config = Service::getConfig('alipay');
        $pay = Pay::alipay($config);
        $result = $pay->verify();
        $amount = $result['total_amount'];
        $out_trade_no = $result['out_trade_no'];
        $trade_status = $result['trade_status'];


        error_log($out_trade_no . "==========" . $trade_status);
        $pay->success();
        $listoreModel =new Litestoreorder();
        if (in_array($result['trade_status'], ['TRADE_SUCCESS'])) {

            $order = $listoreModel->where('order_no',$out_trade_no)->find();
            $listoreModel->where('order_no',$out_trade_no)->update(['pay_status'=>'20','pay_time'=>time()]);
            $profitService = new ProfitService();
            if($order['is_vip'] == 1){
                $profitService->doUserVipProfit($order,$this->countRedis);

                if($order['is_do'] == 1) return;

                $messageService = new MessageService();
                $userProfitModel = new Userotherprofit();
                $userWxModel= new Userweixin();
                $profitList = $userProfitModel->where('type','会员升级')->where('order_id',$order['id'])->select();
                foreach ($profitList as $key=>$val){
                    $wx = $userWxModel->where('user_id',$val['user_id'])->find();
                    if($wx){
                        $param = array();
                        $param['openid'] = $wx['openid'];
                        $param['amount'] = $val['amount'];
                        $messageService->userProfitMessage($this->wxApp,$param);
                    }
                }
            }
        }

        return $pay->success();

    }

    /**
     * 随机获取4个产品
     */
    public function randomProduct(){

        $litestoreGoodModel = new Litestoregoods();
        $list = $litestoreGoodModel->getRandom8();
        foreach ($list as $index => $item) {
            $list[$index]['imageCover'] = cdnurl(explode(",",$item['images'])[0], true);
        }
        $this->success('',$list);

    }


    public function cancel(){

        $orderNo = $this->request->param('orderNo');
        $liteOrderModel = new Litestoreorder();
        $order = $liteOrderModel->where('order_no', $orderNo)->find();
        if($order['pay_status'] != 10){

            $this->error("此订单不可取消");
        }
        $liteOrderModel->where('id',$order['id'])->update(['order_status'=>20]);
        $this->success('成功');
    }


    public function payOrder()
    {
        $orderNo = $this->request->param("orderNo");
        $shopOrderModel = new Litestoreorder();
        $order = $shopOrderModel->where('order_no', $orderNo)->find();



        $newOrderNo = getOrderSn();
        $shopOrderModel->where('id',$order['id'])->update(['order_no'=>$newOrderNo]);
        $info = array();
        $info['orderNo'] = $order['order_no'];

        $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/mall/sxfOrderCallback";


        $req['mno'] = "399240109959044";
        $req['ordNo'] = $newOrderNo;
        $req['amt'] = $order['pay_price'];


        $req['subject'] = "购买商品";
        $req['appletSource'] = "01";
        $req['trmIp'] = get_client_ip();
        $req['notifyUrl'] = $url;


        error_log("===req==".json_encode($req));
        $vbillService = new VbillService();
        $res = $vbillService->pay($req);

        error_log("--=====pay===".json_encode($res));
        $result = json_decode($res, true);
        $bizCode = $result['respData']['bizCode'];
        $bizMsg = $result['respData']['bizMsg'];

        if ($bizCode == '0000') {
            $info['order_no'] = $newOrderNo;
            $info['appId'] = $result['respData']['appId'];
            $info['path'] = $result['respData']['path'];

            $this->success('', $info);
        } else {
            $this->error($bizMsg);
        }

    }


    /**
     * 纷享产品二维码
     */
    public function getProductShare()
    {


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa450f239e42c26fe&secret=f23092b77af8aa3c242b49a96689c27f";
        $ret = Http::get($url);

        $obj = json_decode($ret, true);
        $token = $obj['access_token'];
        $page = $this->request->param('page');
        $scene = $this->request->param('scene');
        $scene = urldecode($scene);
        $user = $this->auth->getUser();
        $uid = $user['id'];
        $productId = $this->request->param('productId');

        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => $page,

        ];
        $name = $uid . "_" . $productId;
        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        error_log("==getProductShare===".json_encode($result));

        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;

        $filename = './uploads/' . $name . '.jpg';

        if (file_exists($filename)) {

            $url = cdnurl("/" . $name . ".jpg", true);
            $this->success('', $url);

            error_log("========已存在图片==========");
        } else {
            base64_image_content($img, $filename);

            $per = 0.5;
            list($width, $height) = getimagesize($filename);
            $n_w = $width * $per;
            $n_h = $height * $per;
            $new = imagecreatetruecolor($n_w, $n_h);
            $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
            imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
            imagedestroy($new);
            imagedestroy($img);

            $config = get_addon_config('alioss');
            $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
            $url = $ret['info']['url'];

            $url = str_replace("http", "https", $url);
            $this->success('', $url);
        }
    }




}
